// pages/index/travelogue/travelogueDetails/travelogueDetails.js

Page({

  /**
   * 页面的初始数据
   */
  data: {
    likeCount: 0,
    isLiked: false,
    
    collectCount: 0,
    isCollected: false,

    commentContent: '', // 评论内容
    travelogueId: '', // 游记 ID
    userId: '', // 用户 ID

    tagList: ['三天两晚自由行', '韩国自由行', '毕业旅行 自由行', '*********************'],
    userId: '', //发评论用户id
    followOrNot: 0, // 0未关注  1已关注
    travelogueList: '',
    commentList: [],
    carouselChart: [],
    upOrNot: 0, // 0未点赞  1已点赞   
    collectOrNot: 0, // 0未收藏  1已收藏  
    travelogueId: 13,
    commentCount: 5,
    travelogueUpCount: '', // 点赞数
    travelogueCollect: 8, //收藏数
    // anoStrategyInfo: [], //其他攻略推荐
    travelogueInfoLike: [], //猜你喜欢的攻略信息
    comm: '', //评论内容
    up: [], //进入页面判断是否点赞过
    coll: [], //进入页面判断是否收藏过
  },
  // 喜欢/点赞
  changeUp() {
    if (this.data.upOrNot != 1) {
      // 对接后端数据库发请求...是否点赞改变
      wx.request({
        url: 'http://localhost:8080/travelogue/travelogueUp',
        method: 'POST',
        header: {
          Authorization: getApp().globalData.authorization
        },

        data: {
          travelogueId: this.data.travelogueList.id,
          userId: 1,
          del: 0
        },
        success: (resp) => {
          console.log(getApp().globalData.authorization)
          console.log('travelogueUpCount', resp)
          this.setData({
            travelogueUpCount: resp.data.data
          });
        }
      })
      this.setData({
        upOrNot: 1
      })
    } else {
      // 对接后端数据库发请求...是否点赞改变
      wx.request({
        url: 'http://localhost:8080/travelogue/travelogueUp/' + this.data.travelogueList.id,
        method: 'DELETE',
        header: {
          Authorization: getApp().globalData.authorization
        },
      })
      this.setData({
        upOrNot: 0
      })
    }
  },
  // 收藏
  changeCollect() {
    if (this.data.collectOrNot != 1) {
      // 对接后端数据库发请求...是否收藏改变
      this.setData({
        collectOrNot: 1
      })
    } else {
      // 对接后端数据库发请求...是否收藏改变
      this.setData({
        collectOrNot: 0
      })
    }
  },
  mess: function () {
    wx.createSelectorQuery().select('.allComment').boundingClientRect(function (rect) {
      // 假设你要滚动到的元素ID是'your-element-id'
      wx.pageScrollTo({
        scrollTop: rect.top, // 滚动到元素的顶部位置
        duration: 300 // 滚动动画的时长，‌单位ms
      });
    }).exec();
  },
  /**
   * 发评论函数
   */
  send(e) {
    wx.request({
      url: 'http://localhost:8080/travelogue/travelogueComment/list',

      method: 'POST',
      header: {
        Authorization: getApp().globalData.authorization
      },
      data: {
        strategyId: this.data.strategyId,
        userId: this.data.loginUserId,
        commentContent: this.data.comm
      },
      success: (resp) => {
        // console.log('评论成功resp', resp)
        if (resp.data.code == 200) {
          wx.showToast({
            title: '发布成功',
            icon: 'success',
            duration: 1500
          })
          this.setData({
            comm: ''
          })
        }
        this.getComment()
        this.getCommentInfo()
      }
    })
  },
  getData() {
    // 根据标签id查名称  传过去多条话题中间表
    var k;
    // console.log("start")
    for (k = 0; k < this.data.tagIds.length; k++) {
      var option = this.data.tagIds[k].subjectId
      wx.request({
        url: `http://localhost:8080/travelogue/travelogueComment/${option}`,
        method: 'GET',
        header: {
          Authorization: getApp().globalData.authorization
        },
        data: {},
        success: (resp) => {
          this.setData({
            tags: this.data.tags.concat(resp.data.data.travelogueName)
          });
        }
      })
    }
  },

  // 查询评论内容...   /strategy/strategy_comment
  getCommentInfo() {
    wx.request({
      url: `http://localhost:8080/travelogue/travelogueComment/list`,
      method: 'GET',
      header: {
        Authorization: getApp().globalData.authorization
      },
      data: {
        travelogueId: this.data.travelogueId
      },
      success: (resp) => {
        this.setData({
          commentInfo: resp.data.rows
        });
      }
    })
  },

  // 关注
  changeFollow() {
    console.log('followOrNot', this.data.followOrNot)
    if (this.data.followOrNot != 1) {
      // 对接后端数据库发请求...关注数改变
      this.setData({
        followOrNot: 1
      })
    } else {
      // 对接后端数据库发请求...关注数改变
      this.setData({
        followOrNot: 0
      })
    }
  },

  // 点赞数
  getUpNum() {
    wx.request({
      url: 'http://localhost:8080/travelogue/travelogueUp/count',
      method: 'GET',
      header: {
        Authorization: getApp().globalData.authorization
      },
      data: {
        travelogueId: this.data.travelogueId
      },
      success: (resp) => {
        console.log(resp)
        this.setData({
          travelogueUpCount: resp.data.data
        });
      }
    })
  },

  // 收藏数
  getCollectNum() {
    wx.request({
      url: 'http://localhost:8080/travelogue/travelogueCollect/count',
      method: 'GET',
      header: {
        Authorization: getApp().globalData.authorization
      },
      data: {
        travelogueId: this.data.travelogueId
      },
      success: (resp) => {

        this.setData({
          travelogueCollect: resp.data.data
        });
      }
    })
  },

  // 点击加入收藏表数据库/取消收藏   /strategy/strategy_collect 
  insertStrategyCollect() {
    this.getCollectResult()
    if (this.data.collectOrNot != 0) { //1 已收藏 取消收藏
      wx.request({
        url: 'http://localhost:8080/travelogue/travelogueCollect/condition',
        method: 'DELETE',
        header: {
          Authorization: getApp().globalData.authorization
        },
        data: {
          travelogueId: this.data.travelogueId,
          userId: this.data.loginUserId
        },
        success: (resp) => {
          // console.log('取消攻略收藏')
          // console.log('travelogueId', this.data.travelogueId)
          // console.log('loginUserId', this.data.loginUserId)
          // console.log('userId', this.data.userId)
          // console.log('是否收藏', resp.data)
          this.getCollectNum()
          this.setData({
            collectOrNot: 0
          })
        }
      })
    } else { //0 未收藏 加入收藏
      wx.request({
        url: 'http://localhost:8080/travelogue/travelogueCollect',
        method: 'POST',
        header: {
          Authorization: getApp().globalData.authorization
        },
        data: {
          travelogueId: this.data.travelogueId,
          userId: this.data.loginUserId
        },
        success: (resp) => {
          // console.log('攻略收藏成功')
          this.getCollectNum()
          this.setData({
            collectOrNot: 1
          })
        }
      })
    }
  },

  // 更新点赞数
  updateUpNum() {
    wx.request({
      url: 'http://localhost:8080/travelogue/travelogueUp/update',
      method: 'POST',
      header: {
        Authorization: getApp().globalData.authorization,
        'Content-Type': 'application/json'
      },
      data: {
        travelogueId: this.data.travelogueId
      },
      success: (resp) => {
        // console.log('Update up count response:', resp.data);

        // 成功更新后重新获取点赞数
        this.getUpNum();
      },
      fail: (error) => {
        console.error('Update up count failed:', error);
      }
    });
  },

  // 更新收藏数
  updateCollectNum() {
    wx.request({
      url: 'http://localhost:8080/travelogue/travelogueCollect/update',
      method: 'POST',
      header: {
        Authorization: getApp().globalData.authorization,
        'Content-Type': 'application/json'
      },
      data: {
        travelogueId: this.data.travelogueId
      },
      success: (resp) => {
        // console.log('Update collect count response:', resp.data);

        // 成功更新后重新获取收藏数
        this.getCollectNum();
      },
      fail: (error) => {
        console.error('Update collect count failed:', error);
      }
    });
  },

  // 新增评论
  addComment: function () {
    // 构造请求数据
    const commentData = {
      commentContent: this.data.commentContent,
      travelogueId: this.data.travelogueId,
      userId: this.data.userId
    };
    // 发送 POST 请求
    wx.request({
      url: 'http://localhost:8080/travelogue/travelogueComment',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        Authorization: getApp().globalData.authorization
      },
      data: commentData,
      success: (resp) => {
        // 成功处理
        console.log('评论成功:', resp.data);

        // 假设服务器返回了新的评论列表
        this.setData({
          commentList: resp.data.rows
        });

        // 清空输入框
        this.setData({
          commentContent: ''
        });
      },
      fail: (err) => {
        // 失败处理
        console.error('评论失败:', err);
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.addComment()
    this.getUpNum()
    this.getCollectNum()

    // 从 options 中获取游记 ID
    const travelogueId = options.id;

    // 设置数据
    this.setData({
      travelogueId: travelogueId
    });

    // 发起请求获取评论数
    this.fetchCommentCount();


    wx.request({
      url: 'http://localhost:8080/travelogue/travelogue/' + 13,
      method: 'GET',
      header: {
        Authorization: getApp().globalData.authorization
      },
      success: (resp) => {
        // console.log(options.id);
        console.log(resp)
        this.setData({
          travelogueList: resp.data.data
        })
      }
    })

    //评论
    wx.request({
      url: 'http://localhost:8080/travelogue/travelogueComment/list',
      method: 'GET',
      header: {
        Authorization: getApp().globalData.authorization
      },
      success: (resp) => {
        // console.log(resp.data)
        this.setData({
          commentList: resp.data.rows
        })
      }
    })

    //新增评论
    wx.request({
      url: 'http://localhost:8080/travelogue/travelogueComment',
      method: 'POST',
      data: {
        comm: this.data.comm
      },
      header: {
        Authorization: getApp().globalData.authorization
      },
      success: (resp) => {
        // console.log(resp.data)

      }
    })

    wx.request({
      url: 'http://localhost:8080/travelogue/travelogueImages/list',
      method: 'GET',
      header: {
        Authorization: getApp().globalData.authorization
      },
      success: (resp) => {
        // console.log(resp)
        this.setData({
          carouselChart: resp.data.rows
        })
      }
    })

    const likeState = wx.getStorageSync('likeState') || {
      count: 0,
      liked: false
    };
    this.setData({
      likeCount: likeState.count,
      isLiked: likeState.liked
    });

    const collectState = wx.getStorageSync('collectState') || {
      count: 0,
      collected: false
    };
    this.setData({
      collectCount: collectState.count,
      isCollected: collectState.collected
    });
  },
  onLike: function () {
    if (this.data.isLiked) {
      this.decrementLike();
    } else {
      this.incrementLike();
    }
  },

  incrementLike: function () {
    const newCount = this.data.likeCount + 1;
    this.setData({
      likeCount: newCount,
      isLiked: true
    });
    wx.setStorageSync('likeState', {
      count: newCount,
      liked: true
    });
  },

  decrementLike: function () {
    const newCount = Math.max(this.data.likeCount - 1, 0);
    this.setData({
      likeCount: newCount,
      isLiked: false
    });
    wx.setStorageSync('likeState', {
      count: newCount,
      liked: false
    });
  },

  onCollect: function () {
    if (this.data.isCollected) {
      this.decrementCollect();
    } else {
      this.incrementCollect();
    }
  },

  incrementCollect: function () {
    const newCount = this.data.collectCount + 1;
    this.setData({
      collectCount: newCount,
      isCollected: true
    });
    wx.setStorageSync('collectState', {
      count: newCount,
      collected: true
    });
  },

  decrementCollect: function () {
    const newCount = Math.max(this.data.collectCount - 1, 0);
    this.setData({
      collectCount: newCount,
      isCollected: false
    });
    wx.setStorageSync('collectState', {
      count: newCount,
      collected: false
    });
  },



  fetchCommentCount: function () {
    const url = `http://localhost:8080/travelogue/travelogueComment/${this.data.travelogueId}/comments/count`;

    wx.request({
      url: url,
      method: 'GET',
      header: {
        Authorization: getApp().globalData.authorization
      },
      success: (resp) => {
        // console.log("commentCount=" + this.data.travelogueId);
        // console.log(resp);

        // 设置评论数
        this.setData({
          commentCount: resp.data.data
        });
      },
      fail: (error) => {
        console.error('请求失败:', error);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})